/**
 * Created by wlh on 16/3/11.
 */

var $ = require("jquery");


function SelectBox(options) {
    //如果没有实例化,执行实例化
    if (!(this instanceof SelectBox)) {
        return new SelectBox(options);
    }

    if (!options) {
        options = {};
    }

    this.defaultData = options.defaultData || [];;
    this.defaultDataUrl = options.defaultDataUrl;
    this.addPostUrl = options.addPostUrl;
    this.placeHodler = options.placeHodler || '输入关键字';
    this.defaultDataTitle = options.defaultDataTitle || '热门搜索';
    this.data = options.data || [];     //默认数据
    this.fetchUrl = options.fetchUrl;   //获取数据URL
    this.fetchKeyword = options.fetchKeyword || 'q';
    this.displayNameKey = options.displayNameKey;   //显示的值
    this.valueKey = options.valueKey;               //选择后保存的值
    this.selectedHandle = options.selectedHandle;   //选择以后的回调
}

SelectBox.prototype.render = function(id) {
    var self = this;
    var div =
        '<div>' +
            '<div><input type="text" placeholder="'+self.placeHodler+'" id="select-box-search"></div><br/>' +
            '<div id="select-box-add"></div>'+
            '<div>' +
                '<h6 id="select-box-default-title">'+self.defaultDataTitle+'</h6>' +
                '<ul id="select-box-list">' +
                '</ul>' +
            '</div>' +
        '</div>';

    $("#"+id).append(div);
    renderData(self.defaultDataTitle, self.defaultData);

    $("#select-box-search").keyup(function() {
        var val = $(this).val()
        if (val) {
            if (self.addPostUrl) {
                $("#select-box-add").html('<span>'+val+'</span>&nbsp;&nbsp;<input type="button" value="添加"/>')
            }
            if (self.fetchUrl) {
                $.getJSON(self.fetchUrl, {q: val}, function(result) {
                    renderData('搜索结果', result);
                }, "json");
            } else {

                renderData('搜索结果', self.data);
            }
        } else {
            $("#select-box-add").html("");
            renderData(self.defaultDataTitle, self.defaultData);
        }
    });

    function renderData(title, data) {
        $("#select-box-default-title").html(title);
        var items = data.map(function(item) {
            return '<li data="'+item[self.valueKey]+'">'+item[self.displayNameKey]+'</li>'
        });
        $("#select-box-list").html(items);

        $("#select-box-list>li").click(function() {
            var val = $(this).attr("data");
            var displayName = $(this).text();
            if (self.selectedHandle && typeof self.selectedHandle == 'function') {
                self.selectedHandle({val: val, displayName: displayName});
            }
        })
    }
}

module.exports = SelectBox;